<template>
  <div>
    <h1>BMI Page!</h1>
    <BMIForm @my-submit="parentSubmit"/>
    <h2>BMI列表</h2>
    <table border="1">
      <thead>
      <tr>
        <th>#</th>
        <th>日期</th>
        <th>身高</th>
        <th>体重</th>
        <th>BMI</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <BMIItem
          v-for="(item, index) of bmiList"
          :key="item.id"
          :item="item"
          :index="index+1"
          @onDel="onDelete"
      ></BMIItem>
      </tbody>
    </table>
  </div>
</template>

<script>
import BMIForm from '@/components/BMIForm';
import BMIItem from '@/assets/BMIItem';

export default {
  data() {
    return {
      bmiList: []
    }
  },
  components: {
    BMIForm,
    BMIItem
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      fetch('http://120.27.209.174:1010/api/v1/bmi').then(res => {
        return res.json()
      }).then(res => {
        this.bmiList = res
      })
    },
    parentSubmit(data) {
      fetch('http://120.27.209.174:1010/api/v1/bmi', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      }).then(res => res.json()).then(() => {
        // console.log(res)
        this.getList()
      })
    },
    onDelete(id) {
      if (confirm('确定要删除数据吗？')) {
        fetch(`http://120.27.209.174:1010/api/v1/bmi/${id}`, {
          method: 'DELETE'
        }).then(res => res.json()).then(() => {
          this.getList()
        })
      }
    }
  }
}
</script>
